﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace MemoDb
{
    public class DictionaryBuilder
    {
        private readonly Hashtable items = new Hashtable();

        public void Add(object key, object value)
        {
            items.Add(key, value);
        }

        public object BuildFor(Type dictionaryType)
        {
            Type type;

            if (IsGenericDictionaryInterface(dictionaryType))
                type = typeof(Dictionary<,>).MakeGenericType(dictionaryType.GetGenericArguments());
            else if (dictionaryType.IsInterface)
                type = typeof(Hashtable);
            else if (dictionaryType.HasParameterlessConstructor())
                type = dictionaryType;
            else
                throw new InvalidOperationException(string.Format("Dictionary type {0} is not supported.", dictionaryType.FullName));

            var dictionary = (IDictionary)Activator.CreateInstance(type);


            foreach (var key in items.Keys)
                dictionary.Add(key, items[key]);

            return dictionary;
        }

        private static bool IsGenericDictionaryInterface(Type dictionaryType)
        {
            return dictionaryType.IsInterface && dictionaryType.IsGenericType &&
                   dictionaryType.GetGenericArguments().Length == 2;
        }
    }
}